<?php
/**
 * 订单类型控制器
 */
declare(strict_types=1);

namespace app\controller\crm;

use app\BaseController;
use app\model\crm\OrderType;
use think\Response;

class OrderTypeController extends BaseController
{
    protected $noNeedLogin = [];
    
    /**
     * 获取订单类型列表
     * @return Response
     */
    public function list(): Response
    {
        try {
            $params = $this->request->get();
            
            $query = OrderType::order('sort_order', 'asc');
            
            // 筛选条件
            if (isset($params['category'])) {
                $query->where('category', $params['category']);
            }
            
            if (isset($params['status'])) {
                $query->where('status', $params['status']);
            } else {
                // 默认只返回启用的类型
                $query->where('status', OrderType::STATUS_ENABLED);
            }
            
            $list = $query->select()->toArray();
            
            return json([
                'code' => 0,
                'msg'  => 'success',
                'data' => $list,
                'timestamp' => time()
            ]);
            
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg'  => $e->getMessage(),
                'data' => null,
                'timestamp' => time()
            ]);
        }
    }
    
    /**
     * 根据订单大类获取类型
     * @param int $category
     * @return Response
     */
    public function getByCategory(int $category): Response
    {
        try {
            $list = OrderType::getEnabledTypes($category);
            
            return json([
                'code' => 0,
                'msg'  => 'success',
                'data' => $list,
                'timestamp' => time()
            ]);
            
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg'  => $e->getMessage(),
                'data' => null,
                'timestamp' => time()
            ]);
        }
    }
}
